package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.beans.TableProcess;
import com.atguigu.gmall.realtime.common.GmallConfig;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Author: Felix
 * Date: 2022/3/14
 * Desc: 业务数据动态分流处理
 */
public class TableProcessFunction extends BroadcastProcessFunction<JSONObject, String, JSONObject> {
    private OutputTag<JSONObject> dimTag;
    private MapStateDescriptor<String, TableProcess> mapStateDescriptor;
    private Connection conn;

    public TableProcessFunction(OutputTag<JSONObject> dimTag, MapStateDescriptor<String, TableProcess> mapStateDescriptor) {
        this.dimTag = dimTag;
        this.mapStateDescriptor = mapStateDescriptor;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        //注册驱动
        Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
        //建立连接
        conn = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER);
    }

    //处理业务流数据
    @Override
    public void processElement(JSONObject jsonObj, ReadOnlyContext ctx, Collector<JSONObject> out) throws Exception {
        //获取表名
        String table = jsonObj.getString("table");
        //获取操作类型
        String type = jsonObj.getString("type");
        //注意：如果使用maxwell bootstrap对历史数据进行处理，类型为bootstrap-insert，统一为insert类型
        if (type.equals("bootstrap-insert")) {
            type = "insert";
            jsonObj.put("type", type);
        }
        //拼接key
        String key = table + ":" + type;
        //获取广播状态
        ReadOnlyBroadcastState<String, TableProcess> broadcastState = ctx.getBroadcastState(mapStateDescriptor);

        //根据key到广播状态中，获取当前处理的这条业务数据所对应的配置信息
        TableProcess tableProcess = broadcastState.get(key);

        if (tableProcess != null) {
            //不管是事实还是维度，在向下游传递数据前，都需要补充 sink_table
            String sinkTable = tableProcess.getSinkTable();
            jsonObj.put("sink_table", sinkTable);
            //将不需要传递到下游的属性过滤掉
            String sinkColumns = tableProcess.getSinkColumns();

            JSONObject dataJsonObj = jsonObj.getJSONObject("data");
            filterColumn(dataJsonObj, sinkColumns);

            //如果配置对象不为null，说明在配置表中找到了对应的配置信息，接下来判读是事实还是维度
            String sinkType = tableProcess.getSinkType();
            if (TableProcess.SINK_TYPE_HBASE.equals(sinkType)) {
                //维度数据  放到维度侧输出流中
                ctx.output(dimTag, jsonObj);
            } else if (TableProcess.SINK_TYPE_KAFKA.equals(sinkType)) {
                //事实数据  放到主流
                out.collect(jsonObj);
            }
        } else {
            System.out.println("No this Key in TableProcess " + key);
        }
    }


    //处理广播流数据   jsonStr:{"database":"","table":"","type":"","data":{}}
    @Override
    public void processBroadcastElement(String jsonStr, Context ctx, Collector<JSONObject> out) throws Exception {
        JSONObject jsonObj = JSON.parseObject(jsonStr);
        JSONObject dataJsonObj = jsonObj.getJSONObject("data");
        //将dataJsonObj封装为一个配置对象TableProcess
        TableProcess tableProcess = dataJsonObj.toJavaObject(TableProcess.class);

        //获取源数据库表名
        String sourceTable = tableProcess.getSourceTable();
        //获取操作类型
        String operateType = tableProcess.getOperateType();
        //获取输出类型   hbase   kafka
        String sinkType = tableProcess.getSinkType();
        //获取输出目的地
        String sinkTable = tableProcess.getSinkTable();
        //获取表中字段    作用1：建表      作用2：过滤
        String sinkColumns = tableProcess.getSinkColumns();
        //获取建表主键
        String sinkPk = tableProcess.getSinkPk();
        //获取建表扩展
        String sinkExtend = tableProcess.getSinkExtend();

        //判断是否是维度配置，如是维度配置，提前将维度表创建出来
        if (TableProcess.SINK_TYPE_HBASE.equals(sinkType) && "insert".equals(operateType)) {
            checkTable(sinkTable, sinkColumns, sinkPk, sinkExtend);
        }
        //拼接广播状态中的key
        String key = sourceTable + ":" + operateType;
        //获取广播状态
        BroadcastState broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //将当前这条配置信息放到广播状态中
        broadcastState.put(key, tableProcess);

    }

    //创建维度表
    private void checkTable(String tableName, String sinkColumns, String pk, String ext) {
        //null值处理
        if (pk == null) {
            pk = "id";
        }
        if (ext == null) {
            ext = "";
        }
        //拼接维度建表语句
        StringBuilder createSql = new StringBuilder("create table if not exists " + GmallConfig.PHOENIX_SCHEMA + "." + tableName + "(");

        //使用逗号对字符串进行分割，获取所有表中字段
        String[] fieldArr = sinkColumns.split(",");
        for (int i = 0; i < fieldArr.length; i++) {
            String field = fieldArr[i];
            if (field.equals(pk)) {
                createSql.append(field + " varchar primary key");
            } else {
                createSql.append(field + " varchar ");
            }
            //如果是最后一个字段，不需要加逗号，其它的都加
            if (i < fieldArr.length - 1) {
                createSql.append(",");
            }
        }

        createSql.append(") " + ext);
        System.out.println("在Phoenix中建表的SQL:" + createSql);
        PreparedStatement ps = null;
        try {
            //获取数据库操作对象
            ps = conn.prepareStatement(createSql.toString());
            //执行SQL
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("在Phoenix中创建维度表失败~~~");
        } finally {
            //释放资源
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //字段过滤   //dataJsonObj :{"tm_name":"bbb","logo_url":"dfasf","id":14}  sinkColumns: id,tm_name
    private void filterColumn(JSONObject dataJsonObj, String sinkColumns) {
        String[] fieldArr = sinkColumns.split(",");
        List<String> fieldList = Arrays.asList(fieldArr);
        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry -> !fieldList.contains(entry.getKey()));
    }
}
